<template>
  <div id="lightCtrl" class="wrapper" style="overflow: hidden">
    <div class="py-3 pl-5" style="border-bottom: 1px solid #c4c4c4">
      <el-radio v-model="searchType" :label="0" class="mr-3">当前框选的RTU单灯</el-radio>
      <el-radio v-model="searchType" :label="2" class="mr-3">当前框选的NB单灯</el-radio>
      <el-radio v-model="searchType" :label="1" class="mx-2">单灯分组</el-radio>
      <el-select v-if="searchType==1" class="w140" v-model="groupId" slot="prepend" placeholder="请选择" size="small" @change="getCurGroup">
        <el-option v-for="(item,index) in groups" :key="index" :label="item.GroupName+'('+item.typeName+')'" :value="item.Id"></el-option>
      </el-select>
      <!--<el-radio v-model="searchType" :label="2" class="mr-0 ml-3">NB单灯分组：</el-radio>-->
      <!--<el-select class="w140" size="small" v-model="nb_lightGroup">-->
        <!--<el-option v-for="(item,index) in global.BoxTypes" :key="index" :label="item" :value="index+1"></el-option>-->
      <!--</el-select>-->
    </div>

    <div>
      <!--灯杆表格-->
      <div class="float-left p-3"  style="border-right: 1px solid #c4c4c4;width: 600px;">
        <el-table ref="poleTable" :data="gridData" :height="545" highlight-current-row @selection-change="selsChange" >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50" ></el-table-column>
          <el-table-column align="center" label="灯杆" prop="PoleNo"></el-table-column>
          <el-table-column align="center" label="设备地址" prop="DevAddr" width="160"></el-table-column>
          <el-table-column align="center" label="下发结果" width="80" prop="result">
            <template slot-scope="scope">
              <template v-if="scope.row.result===1"><i class="circle success" ></i>成功</template>
              <template v-else-if="scope.row.result===0"><i class="circle error" ></i>失败</template>
              <template v-else>{{scope.row.result}}</template>
            </template>
          </el-table-column>
          <el-table-column align="center" label="失败原因" prop="resultInfo" width="120"></el-table-column>
        </el-table>
        <div class="mt-2">
          <label>下发结果：</label>
          <div class="progress  w200 d-inline-block" style="height: 16px;vertical-align: middle">
            <div ref="progressBar" class="progress-bar progress-bar-striped" role="progressbar" style="width:0" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
          </div>
        </div>
      </div>
      <div class="float-left p-3 w450" >
        <!--灯火列表-->
        <ul class="light-group d-flex justify-content-between" v-if="searchType==2||curGroup.Type==3">
          <li v-for="index in lamps" :key="index" class="mr-3 d-flex flex-column justify-content-center align-items-center"
              :class="{active:lightSels.indexOf(index)!=-1}" @click="lightSelFun(index)">
            <img ref="bulbImg" :src="imgSrc" width="40" height="64">
            <label class="mt-2">火{{index}}</label>
          </li>
        </ul>
        <!--调光-->
        <div class="block ur_border mt-4 p-3">
          <el-radio-group v-model="actionType">
            <el-radio :label="1" class="w110">关灯</el-radio>
            <el-radio :label="2" class="w110">开灯</el-radio>
            <el-radio :label="3" class="w110">调光</el-radio>
          </el-radio-group>
          <el-slider v-model="lightLevel" show-input class="ml-2 mt-2" :disabled="isSlider"></el-slider>
        </div>
        <div class="mt-3 d-flex align-items-center">
          <label >操作密码：</label>
          <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
            <el-input type="password" placeholder="请输入操作密码" class="input-with-select w200" :class="{'is-error':errors.has('pwd')}" size="small" v-model="operatePwd" v-validate="'required'" name="pwd">
              <el-button type="password" slot="append" class="ur-btn ur-btn-primary" :disabled="btnState" @click="send"><i class="iconfont icon-queding"></i>下发</el-button>
            </el-input>
          </el-tooltip>
        </div>
      </div>
    </div>

  </div>
</template>

<script type="text/ecmascript-6">
  import api from 'api/api'
  import fetch from 'api/fetch'

  export default {
    components: {},
    props: {
      poles:{
        type:Array,
        default:function () {
          return []
        }
      },
    },
    data() {
      return {
        searchType:0,
        lightLevel:0,
        actionType:1,
        lightSels:[1,2,3],
        isSlider:true,
        operatePwd:'',
        gridData:[],
        sels:[],
        lamps:3,
        imgSrc:'static/image/comm/off_light.png',
        groupId:-1,
        groups:[],
        curGroup:{},
        btnState:false
      }
    },
    watch: {
      actionType(val){
        if(val==3){
          this.isSlider=false
        }else{
          this.isSlider=true
          this.lightLevel=val==2?100:0
        }
      },
      searchType(val){
        if(val==0){
          if (this.groups.length) this.groupId = this.groups[0].Id
        }
        this.querLightInfo()
      }
    },
    computed: {},
    methods: {
      getCurGroup(id){
        this.groups.map(r => {
          if (r.Id == id) this.curGroup = r
        })
        this.querLightInfo()
      },
      indexMethod(index) {
        return index + 1
      },
      selsChange(sels) {
        this.sels = sels
        this.sels.splice(0,0)
      },
      lightSelFun(index){
        if(this.lightSels.indexOf(index)!=-1){
          let sIndex=this.lightSels.indexOf(index)
          this.lightSels.splice(sIndex,1)
        }else{
          this.lightSels.push(index)
        }
      },
      querLightInfo(){
        this.gridData=[]
        if (this.searchType == 0) {//rtu单灯
          if (this.poles.length) {
            this.poles.map(r => {
              if(r.ChannelMode==1){
                r['result'] = ''
                r['resultInfo'] = ''
                this.gridData.push(r)
              }
            })
          }
          this.gridData.splice(0, 0)
        }else if (this.searchType == 2) {//nb单灯
          if (this.poles.length) {
            this.poles.map(r => {
              if(r.ChannelMode==2){
                r['result'] = ''
                r['resultInfo'] = ''
                this.gridData.push(r)
              }
            })
          }
          this.gridData.splice(0, 0)
        } else if (this.searchType == 1) {
          this.GetPoleByGroup()
        }
      },
      queryGroup(){
        fetch.queryGroup()
          .then(r => {
            if(r.data.length==0) return
            r.data.map(r => {
              if (r.Type == 2) {
                this.groups.push(Object.assign(r, {typeName: 'RTU'}))
              } else if (r.Type == 3) {
                this.groups.push(Object.assign(r, {typeName: 'NB'}))
              }
            })
            this.curGroup = this.groups[0]
            this.groupId = this.groups[0].Id
          })
      },
      GetPoleByGroup() {
        // let type = this.curGroup.typeName == 'RTU' ? 2 : 3
        let url=''
        if(this.curGroup.typeName == 'RTU'){
          url='/Group/GetRtuPoleByGroup'
        }else {
          url='/Group/GetNBPoleByGroup'
        }
        api.fetchSimple(url, { groupId: this.groupId, value: '' }).then(r => {
          this.gridData = r.data
          if (this.gridData.length != '') {
            this.gridData.map(r=>{
              r['PoleNo'] = r.No
            })
            this.gridData.splice(0,0)
          }
        })
      },
      send() {
        let poleIds=[]
        if(!this.lightSels.length){
          return this.$message.warning('请选择灯泡')
        }
        if(this.sels.length==0) return this.$message.warning('未选择灯杆')
        this.$validator.validateAll().then((res) => {
          if (res) {
            let pIndex = 1
            this.$store.commit('user/SET_USER_PWD', this.operatePwd)
            this.sels.map((pole, index, arr) => {
              pole.result = '下发控制中...'
              let url,data
              if(this.searchType==0||(this.searchType==1&&this.curGroup.Type==2)){
                url='/Communication/Rtu/AFN05F2'
                data={devAddr:pole.BoxDevAddr,lightLevel:this.lightLevel,rtuXh:pole.RtuXh}
              }else if(this.searchType==2||(this.searchType==1&&this.curGroup.Type==3)){
                url='/Communication/NB/NBSwitchController'
                data={tnDevAddr:pole.PoleDevAddr||pole.DevAddr,lightLevel:this.lightLevel,lampNos:this.lightSels}
              }
              api.fetchSimple(url,data)
                .then(async r => {
                  poleIds.push(pole.PoleId)
                  this.btnState = true
                  if (r.err) {
                    if(this.page=='gis'){
                      this.$message.error(r.err)
                      this.$refs.bulbImg.map(img=>{
                        img.attributes[0]['value']='static/image/comm/off_light.png'
                      })
                    }
                    pole.result = 0
                    pole.resultInfo = r.err
                  }
                  else {
                    if (this.page == 'gis') {
                      this.$message.success(['关灯', '开灯', '调光'][this.actionType - 1] + '成功')
                      if (this.lightLevel != 0) {
                        this.$refs.bulbImg.map(img => {
                          img.attributes[0]['value'] = 'static/image/comm/light.png'
                        })
                      }
                    }
                    this.callNum.success++
                    pole.result = 1
                    pole.resultInfo = '/'
                  }
                  let total = this.sels.length
                  let pcen = Math.round(pIndex / total * 100) > 100 ? 100 : Math.round(pIndex / total * 100)
                  this.updateBar(pcen)
                  pIndex++
                  if (pcen==100) {
                    this.btnState=false
                    this.clearResult(poleIds,'end')
                  }
                })
            })
          }
        })
      },
      clearResult(poleIds,type){
        this.$refs.poleTable.clearSelection()
        this.gridData.forEach(box => {
          let index=poleIds.indexOf(box.PoleId)
          if (index != -1) this.$refs.poleTable.toggleRowSelection(box)
          if(type=='start'){//操作前清空结果
            this.$refs.progressBar.style.width =0
            this.$refs.progressBar.textContent =''
            box.result=''
            box.resultInfo = ''
            box.opereaTime = ''
          }
        })
      },
      updateBar(pcen){//更新进度条宽度
        this.$refs.progressBar.style.width = pcen + '%'
        this.$refs.progressBar.textContent = pcen + '%'
      },
    },
    created() {
      this.queryGroup()
      this.querLightInfo()
    },
    mounted() {
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">
  .light-group{
    li{width: 104px;height: 104px;border:1px solid #ccc;border-radius: 4px;
      &.active{background: #e4f4ff;border-color: #0c8eec}
    }
  }
</style>
